//
//  HYFAuthController.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/20.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class HYFAuthController: UIViewController {
    
    //MARK: 让 webView 替代 view
    override func loadView() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        
        print(urlString)
        
        let url = NSURL(string: urlString)
        guard let u = url else {
            return
        }
        
    let request = NSURLRequest(URL: u)
        
    webView.loadRequest(request)
        //MARK: 监听webview
    webView.delegate = self
    view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        //插入进度条
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
        
        setupNav()
    }
    
    //MARK:设置导航栏按钮
    func setupNav(){
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(HYFAuthController.autoFillClick))
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HYFAuthController.cancelClick))
        
        navigationItem.title = "微博登录"
    }
    
    @objc  private func cancelClick(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillClick(){
        
        print("自动填充")
        
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPassword)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
        //MARK:懒加载 webView
    private lazy var webView:UIWebView = UIWebView()
    private lazy var progressView:HYFAutoProgressView = HYFAutoProgressView()
    
}


extension HYFAuthController:UIWebViewDelegate {
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
       progressView.startAnim()
       SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        progressView.endAnim()
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    //监听 webview 将要加载的 request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString

        if  let u = urlString where u.hasPrefix(APPREDIRECT_URI){
            
            let query = request.URL?.query
            
            if let q = query {
                
                let code = q.substringFromIndex("code=".endIndex)
             
                
                HYFUserAccountViewModel.sharedTools.loadUserAccount(code, isSuccess: { (isSuc) in
                    
                    print(isSuc)
                    
                    if !isSuc{
                        print("请求失败")
                        return
                    }
                    
                    //先关闭当前界面
                    self.dismissViewControllerAnimated(false, completion: {
                        
                       NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                    })
                    
                })
                
                //不让再继续加载回调页
                return false
            }
        }
        return true
    }
}







